const exec = require('child_process').exec;
const spawn = require('child_process').spawn;

function run(txt, show=true){
    if (show) {
        console.log("cmd run: "+txt);
    }
    exec(txt);
}

function get(txt, show=true){
    return new Promise(function (resolve, reject) {
        exec(txt, function(err, stdout, stderr){
            if (show) {
                console.log("cmd get: "+txt);
            }
            if (err) {
                reject(stderr);
            }
            else{
                resolve(stdout);
            }
        });
    })
}

//需要手动传入换行符“\n”
function command(cmd, args=[], outcb=null, closecb=null) {
    let proc = spawn(cmd, args, {stdio:'pipe', detached:false});
    proc.input = function(str) {//终端输入
        if (!this.exited) {
            this.stdin.write(str);
        }
    }
    proc.forcedClose = function() {//强制结束
        this.kill(9);
    }
    proc.on('exit', function(code) {
        this.exited = true;
    });
    if (outcb) {
        proc.stdout.on('data', function (data) {
            outcb(null,data,proc);
        });
        proc.stderr.on('data', function (data) {
            outcb(data,null,proc);
        });
        proc.on('error', function (err) {
            outcb(err,null,proc);
        });
    }
    if (closecb) {
        proc.on('close', function(code) {
            closecb(code);
        });
    }
    return proc;
}

exports.run = run;
exports.get = get;
exports.command = command;